<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class IpMiddleware
{


    public function isBlock(): bool
    {
        $envIp = admin_setting("IP_WHITE_LIST", '');
        if (!$envIp)
            return false;

        $envIp .= config('sitesetting.IP_WHITE_LIST', '');

        return $envIp && !Str::contains($envIp, request()->ip());
    }

    public function isOutUser()
    {
        if ($user = \Admin::user()) {
            if ($user->isAdministrator() || $user->isRole('outside_login'))
                return true;
        }
        return false;
    }

    public function pathExcept(Request $request)
    {
        if ($request->method() === 'POST' && Str::contains($request->path(), 'auth/login')) {
            return true;
        }

        return Str::contains($request->path(), [
            'look_ip',
            'auth/logout',
            'auth/outside_login',
        ]);
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if ($this->pathExcept($request))
            return $next($request);

        if ($this->isBlock() && !$this->isOutUser()) {
            abort(403);
        }

        return $next($request);
    }
}
